package com.nbjtjc.safe.service.edu;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.edu.EduPlanItemMapper;
import com.nbjtjc.safe.mapper.edu.EduPlanListMapper;
import com.nbjtjc.safe.mapper.sys.SysDeptMapper;
import com.nbjtjc.safe.mapper.sys.SysUserMapper;
import com.nbjtjc.safe.model.cost.CostBudgetItem;
import com.nbjtjc.safe.model.cost.CostBudgetPlan;
import com.nbjtjc.safe.model.edu.EduPlanItem;
import com.nbjtjc.safe.model.edu.EduPlanList;
import com.nbjtjc.safe.model.edu.EduRequirementInvestigation;
import com.nbjtjc.safe.model.know.SafeKnowledge;
import com.nbjtjc.safe.model.sys.SysNotice;
import com.nbjtjc.safe.service.sys.SysNoticeService;
import com.nbjtjc.safe.util.FileUtil;
import com.nbjtjc.safe.util.MyShiroUtils;
@Service
public class EduPlanListService {
	@Autowired
    private EduPlanListMapper eduPlanListMapper;
	@Autowired
    private EduPlanItemMapper eduPlanItemMapper;
    @Autowired
    private FileUtil fileUtil;
    @Autowired
    private SysDeptMapper sysDeptMapper;

    
	//非按模板生成项目，旧新增和更新接口
//    @Transactional(rollbackFor = {Throwable.class})
//	public Result add(EduPlanList eduPlanList) {
//		// TODO Auto-generated method stub
//    	Result result=new Result();
//    	if(ObjectUtil.isNull(eduPlanList)){
//    		result.setData("培训计划不能为空");
//    		return result;
//    	}
//    	//无主键或主键不在原表中则为新建培训计划，插入数据
//    	if(ObjectUtil.isNull(eduPlanList.getId())
//    			||ObjectUtil.isNull(eduPlanListMapper.selectByPrimaryKey(eduPlanList.getId()))){
//	        //同样年份一直能有一个
//	        if(ObjectUtil.isNotNull(eduPlanList.getCreateYear())){
//	        	EduPlanList eduPlanListYear=new EduPlanList();
//	        	eduPlanListYear.setCreateYear(eduPlanList.getCreateYear());
//	        	eduPlanListYear.setCompanyId(MyShiroUtils.getCompanyId());
//
//	        	if(CollectionUtil.isNotEmpty(eduPlanListMapper.search(eduPlanListYear))){
//		        	result.setFalse("该年份已有教育培训计划，不能重复增加");
//		            return result;
//	        	}
//	        }else{
//	        	result.setFalse("年份不能为空");
//	            return result;
//	        }
//    		
//        	//记录当前用户单位作为预算计划公司
//        	int  companeyId= MyShiroUtils.getCompanyId();
//        	eduPlanList.setCompanyId(companeyId);
//        	eduPlanList.setCompanyName(sysDeptMapper.findNameById(companeyId));
//        	eduPlanList.setCreateDate(new Date());
//        	eduPlanList.setCreateId(MyShiroUtils.getSessionUserId());
//        	
//    		int res=eduPlanListMapper.insertSelective(eduPlanList);
//	        if(res==0){
//	            result.setFalse("插入失败");
//	            return result;
//	        }
//	        //为方便测试不用每次输计划内容，计划内容为空时不改变计划内容表  
//	        if(CollectionUtil.isNotEmpty(eduPlanList.getEduPlanItems())){
//        		
//        		
//	        	result = insertEduPlanItem(eduPlanList);   
//    	        if(result.isSuccess()==false){
//    	            return result;
//    	        }
//	        }
//    	}else{
//        	eduPlanList.setModifyDate(new Date());
//        	eduPlanList.setModifyId(MyShiroUtils.getSessionUserId());
//    	 	int res=eduPlanListMapper.updateByPrimaryKeySelective(eduPlanList);
//	        if(res==0){
//	            result.setFalse("更新失败");
//	            return result;
//	        }
//	        //为方便测试不用每次输计划内容，计划内容为空时不改变计划内容表  
//	        if(CollectionUtil.isNotEmpty(eduPlanList.getEduPlanItems())){
//
//		        int t = eduPlanList.getId();
//		        res = eduPlanItemMapper.deleteByPlanId(t);     
//		        if(res==0){
//		            result.setFalse("删除计划项目失败");
//		            return result;
//		        }
//		        result = insertEduPlanItem(eduPlanList);     
//		        if(result.isSuccess()==false){
//		            return result;
//		        }
//	        }
//    	}
//        result.setData(eduPlanList);
//
//		return result;
//	}
	
    private Result insertEduPlanItem(EduPlanList eduPlanList){
        Result result=new Result();
    	if(CollectionUtil.isEmpty(eduPlanList.getEduPlanItems())){
            result.setFalse("插入对象为空");
        	return result;

	    }
    	//将planItems的PlanId都设为当前eduPlanList的ID
    	List<EduPlanItem> planItems =  eduPlanList.getEduPlanItems();
		for(EduPlanItem planItem: planItems){
			planItem.setPlanId(eduPlanList.getId());
		}
    	int res=eduPlanItemMapper.insertList(eduPlanList.getEduPlanItems());
    	if(res==0){
            result.setFalse("插入计划项目失败");
            return result;

        }
        result.setData(eduPlanList.getEduPlanItems());
    	return result;
    }
    
	public Result delete(int id) {
		// TODO Auto-generated method stub
        Result result=new Result();
        if(ObjectUtil.isNull(id)){
            result.setFalse("删除对象不能为空");
            return result;
        }
        int res = eduPlanListMapper.deleteByPrimaryKey(id);
        if(res==0){
            result.setFalse("删除失败");
            return result;
        }
        return result;
	}
	
	public Result find(EduPlanList eduPlanList) {
		// TODO Auto-generated method stub
		Result result = new Result();
		PageHelper.startPage(eduPlanList.getPageCurrent(), eduPlanList.getPageSize());
		if(ObjectUtil.isNull(eduPlanList.getCompanyId())||eduPlanList.getCompanyId()<=0){
			eduPlanList.setCompanyId(MyShiroUtils.getCompanyId());
		}
		List<EduPlanList> eduPlanLists = eduPlanListMapper.search(eduPlanList);
		result.setData(new PageInfo<>(eduPlanLists));

		return result;
	}
	
	public Result findDetail(EduPlanList eduPlanList) {
		// TODO Auto-generated method stub
		Result result = new Result();
		PageHelper.startPage(eduPlanList.getPageCurrent(), eduPlanList.getPageSize());
		if(ObjectUtil.isNull(eduPlanList.getCompanyId())||eduPlanList.getCompanyId()<=0){
			eduPlanList.setCompanyId(MyShiroUtils.getCompanyId());
		}
		List<EduPlanList> eduPlanLists = eduPlanListMapper.searchDetail(eduPlanList);
		result.setData(new PageInfo<>(eduPlanLists));

		return result;
	}
	
	  public Result findSubcompany(EduPlanList eduPlanList) {
	      Result result = new Result();
	      PageHelper.startPage(eduPlanList.getPageCurrent(), eduPlanList.getPageSize());
	      if(ObjectUtil.isNull(eduPlanList.getCompanyId())||eduPlanList.getCompanyId()==-1){
	    	  result.setFalse("缺少公司ID，无法据此查看下级公司计划");
	    	  return result;
	      }
	      	List<EduPlanList> eduPlanLists = eduPlanListMapper.searchSubcompany(eduPlanList.getCompanyId());
	      result.setData(new PageInfo<>(eduPlanLists));

	      return result;
	  }
	//按模板生成项目的新增和更新
    @Transactional(rollbackFor = {Throwable.class})
	public Result addByTemplet(EduPlanList eduPlanList) {
		Result result = new Result();
    	if(ObjectUtil.isNull(eduPlanList)){
    		result.setData("培训计划不能为空");
    		return result;
    	}
    	//主键为空或库中无此主键则为新建，插入数据
    	if(ObjectUtil.isNull(eduPlanList.getId())
    			||ObjectUtil.isNull(eduPlanListMapper.selectByPrimaryKey(eduPlanList.getId()))){
    		//同样年份一直能有一个
	        if(ObjectUtil.isNotNull(eduPlanList.getCreateYear())){
	        	EduPlanList eduPlanListYear=new EduPlanList();
	        	eduPlanListYear.setCreateYear(eduPlanList.getCreateYear());
	        	eduPlanListYear.setCompanyId(MyShiroUtils.getCompanyId());
	        	if(CollectionUtil.isNotEmpty(eduPlanListMapper.search(eduPlanListYear))){
		        	result.setFalse("该年份已有教育培训计划，不能重复增加");
		            return result;
	        	}
	        }else{
	        	result.setFalse("年份不能为空");
	            return result;
	        }
	        
        	//记录当前用户单位作为预算计划公司
        	int  companeyId= MyShiroUtils.getCompanyId();
        	eduPlanList.setCompanyId(companeyId);
        	eduPlanList.setCompanyName(sysDeptMapper.findNameById(companeyId));
        	eduPlanList.setCreateDate(new Date());
        	eduPlanList.setCreateId(MyShiroUtils.getSessionUserId());
	        
	        //新增计划
    		int res=eduPlanListMapper.insertSelective(eduPlanList);
	        if(res==0){
	            result.setFalse("插入失败");
	            return result;
	        }
	        
	        //获取新建预算计划的ID，以此创建后续项目、二级项目、月度预算
	        if(eduPlanList.getId() == 0){
	            result.setFalse("获取新建预算计划的ID失败");
	            return result;
	        }
	        //根据模板创建计划项目
	        res = eduPlanItemMapper.insertItemByTemplet(eduPlanList.getId());
	        if(res==0){
	            result.setFalse("创建教育培训计划项目失败");
	            return result;
	        }
	        

	        
    	}else{	
        	eduPlanList.setModifyDate(new Date());
        	eduPlanList.setModifyId(MyShiroUtils.getSessionUserId());
    		//否则更新数据
    	 	int res=eduPlanListMapper.updateByPrimaryKeySelective(eduPlanList);
	        if(res==0){
	            result.setFalse("更新失败");
	            return result;
	        }
    		//更新项目内容
        	if(CollectionUtil.isNotEmpty(eduPlanList.getEduPlanItems())){
        		for(EduPlanItem eduPlanItem:eduPlanList.getEduPlanItems()){
        			if(ObjectUtil.isNotNull(eduPlanItem.getId())){
        				res=eduPlanItemMapper.updateByPrimaryKeySelective(eduPlanItem);
       	        	 if(res==0){
    	        		 result.setFalse("更新教育培训计划项目失败");
    			         return result;
    	        	 }
        			}else{
        				result.setData(eduPlanItem);
        				result.setFalse("待更新项目未传ID，更新失败");
        				return result;
        			}
        		}
        	}
    	}
        result.setData(eduPlanList);
		return result;
    }

	//导入预算计划excel
    public Result addBatch(MultipartFile multipartFile,EduPlanList eduPlanList) throws IOException {
        Result result=new Result();
    	if(ObjectUtil.isNull(eduPlanList)||ObjectUtil.isNull(eduPlanList.getId())){
    		result.setFalse("培训计划为空或无Id");
    		return result;
    	}
    	List<EduPlanList> eduPlanLists = eduPlanListMapper.searchDetail(eduPlanList);
    	if(CollectionUtil.isEmpty(eduPlanLists)){
    		result.setFalse("数据库中该培训计划为空");
    		return result;
    	}else if(eduPlanLists.size()>1){
    		result.setFalse("数据库中该培训计划不唯一");
    		return result;
    		}else
	    	{
	    		eduPlanList = eduPlanLists.get(0);
	    	}
    	
    	
    	String fileName=multipartFile.getOriginalFilename();
        File targetFile=new File(fileUtil.getFilePath()+multipartFile.getOriginalFilename());
        if(!targetFile.getParentFile().exists()){
            targetFile.getParentFile().mkdirs();
        }
        multipartFile.transferTo(targetFile);
        if(fileName.endsWith("xls")){
            result = readXls(targetFile,eduPlanList);
        }else if(fileName.endsWith("xlsx")){
        	result = readXlsx(targetFile,eduPlanList);
        }else{
        	result.setFalse("传入文件不是excel表格，请检查");
        	return result;
        }
        return result;
    }
    
  //导入xls
    public Result readXls(File excelFile,EduPlanList eduPlanList) throws IOException {
    	Result result=new Result();
    	if(CollectionUtil.isEmpty(eduPlanList.getEduPlanItems())){
    		result.setFalse("数据库中该培训计划项目为空");
    		return result;
    	}
        InputStream is = new FileInputStream(excelFile);
        // HSSFWorkbook 标识整个excel
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
        
        HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
        //获取excel表中数据
        for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
            // HSSFRow表示行
            HSSFRow hssfRow = hssfSheet.getRow(rowNum);
//            int minColIx = hssfRow.getFirstCellNum();
//            int maxColIx = hssfRow.getLastCellNum();
            eduPlanList.getEduPlanItems().get(rowNum-1).setTrainee(hssfRow.getCell(2).getStringCellValue());
            eduPlanList.getEduPlanItems().get(rowNum-1).setImplementDate(hssfRow.getCell(3).getStringCellValue());
            eduPlanList.getEduPlanItems().get(rowNum-1).setTrainMode(hssfRow.getCell(4).getStringCellValue());
        }
        


	      int  res = eduPlanItemMapper.deleteByPlanId(eduPlanList.getId());     
	        if(res==0){
	            result.setFalse("删除计划项目失败");
	            return result;
	        }
	        result = insertEduPlanItem(eduPlanList);     
	        if(result.isSuccess()==false){
	            return result;
	        }
	        
        result.setData(eduPlanList);

        return result;
    }
    
    //导入xlsx
    public  Result readXlsx(File excelFile,EduPlanList eduPlanList) throws IOException {
    	Result result=new Result();
    	
    	if(CollectionUtil.isEmpty(eduPlanList.getEduPlanItems())){
    		result.setFalse("数据库中该培训计划项目为空");
    		return result;
    	}
        InputStream is = new FileInputStream(excelFile);
        // XSSFWorkbook 标识整个excel
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);

        XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
        //获取excel表中数据
       
        //获取excel表中数据
        for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
            // XSSFRow表示行
            XSSFRow xssfRow = xssfSheet.getRow(rowNum);
//            int minColIx = xssfRow.getFirstCellNum();
//            int maxColIx = xssfRow.getLastCellNum();
            eduPlanList.getEduPlanItems().get(rowNum-1).setTrainee(xssfRow.getCell(2).getStringCellValue());
            eduPlanList.getEduPlanItems().get(rowNum-1).setImplementDate(xssfRow.getCell(3).getStringCellValue());
            eduPlanList.getEduPlanItems().get(rowNum-1).setTrainMode(xssfRow.getCell(4).getStringCellValue());
        }
        


	      int  res = eduPlanItemMapper.deleteByPlanId(eduPlanList.getId());     
	        if(res==0){
	            result.setFalse("删除计划项目失败");
	            return result;
	        }
	        result = insertEduPlanItem(eduPlanList);     
	        if(result.isSuccess()==false){
	            return result;
	        }
        
        
        result.setData(eduPlanList);

        return result;
    	
    	
    }


}
